package com.niodata.dp.monitor.common.util;


import com.niodata.dp.monitor.common.entity.MailItem;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.log4j.Logger;

public class MailSendUtil {

  private static Logger logger = Logger.getLogger(MailSendUtil.class.getName());
  private static ExecutorService executorService = Executors.newCachedThreadPool();

  public static void sendSimpleEmail(MailSource mailSource, MailItem mailItem) {
    executorService.submit(new Runnable() {
      @Override
      public void run() {
        SimpleEmail email = new SimpleEmail();
        // (【smtp.163.com】，【smtp.sohu.com】)
        email.setHostName(mailSource.getHostName());
        try {
          email.addTo(mailItem.getRecipient());
          email.setAuthentication(mailSource.getUsername(), mailSource.getPassword());
          email.setFrom(mailSource.getUsername());
          email.setSmtpPort(mailSource.getSmtpPort());
          email.setSubject(mailItem.getSubject());
          email.setMsg(mailItem.getSendMsg());
          email.send();
        } catch (EmailException ex) {
          logger.error("send email error", ex);
        }
      }
    });
  }

  public static MailSource buildMailSource() {
    ConfigUtil config = ConfigUtil.getInstance();
    MailSource source = new MailSource();
    source.setHostName(config.getString("mail.hostName"));
    source.setUsername(config.getString("mail.username"));
    source.setPassword(config.getString("mail.password"));
    source.setSmtpPort(Integer.valueOf(config.getString("mail.smtpPort")));
    return source;
  }

}
